//网站最后更新时间（版本更新需更改）
var siteLastUpdateTime = '2019年12月02日19点';

//网站开始时间
var siteBeginRunningTime = '2018-07-25 20:00:00';
//文章详情默认地址
var articleDetilUrl = '/front/article/articleDetil?articleId=';
//按时间归档地址
var articleMonthUrl = '';

window.onload = function () {
    var oDiv = document.getElementsByClassName('roll')[0];
    var oUl = oDiv.getElementsByTagName('ul')[0];
    var aLi = oUl.getElementsByTagName('li');

    var now = 0;
    for (var i = 0; i < aLi.length; i++) {
        aLi[i].index = i;
    }

    function next() {
        now++;
        if (now == aLi.length) {
            now = 0;
        }
        startMove(oUl, {top: -26 * now})
    }

    //设置广播滚动时间
    var timer = setInterval(next, 3000);
    oDiv.onmouseover = function () {
        clearInterval(timer);
    };
    oDiv.onmouseout = function () {
        timer = setInterval(next, 3000);
    }
};


// 广告上下滚动
function getStyle(obj, name) {
    if (obj.currentStyle) {
        return obj.currentStyle[name];
    } else {
        return getComputedStyle(obj, false)[name];
    }
}

function startMove(obj, json, doEnd) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function () {
        var oStop = true;
        for (var attr in json) {
            var cur = 0;
            if (attr == 'opacity') {
                cur = Math.round(parseFloat(getStyle(obj, attr)) * 100);
            } else {
                cur = parseInt(parseInt(getStyle(obj, attr)));
            }
            var speed = (json[attr] - cur) / 6;
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
            if (cur != json[attr]) {
                oStop = false;
            }
            if (attr == 'opacity') {
                obj.style.filter = 'alpha(opacity:' + (speed + cur) + ')';
                obj.style.opacity = (speed + cur) / 100;
            } else {
                obj.style[attr] = speed + cur + 'px';
            }
        }
        if (oStop) {
            clearInterval(obj.timer);
            if (doEnd) doEnd();
        }
    }, 30);
}

//填充文章
function putInArticle(data) {
    $('.articles').empty();
    var articles = $('.articles');
    $.each(data, function (index, obj) {
        if (index != data.length) {
            var articleType = '';
            if (obj['articleType'] == 'YC') {
                articleType = '原创';
            }
            if (obj['articleType'] == 'ZZ') {
                articleType = '转载';
            }
            var center = $('<div class="center">' +
                '<header class="article-header">' +
                '<h1 itemprop="name">' +
                '<a class="article-title" href="' + articleDetilUrl + obj.id + '" target="_blank">' + obj.title + '</a>' +
                '</h1>' +
                '<div class="article-meta row">' +
                '<span class="articleType am-badge am-badge-success">' + articleType + '</span>' +
                '<div class="articlePublishDate">' +
                '<i class="am-icon-calendar"><a class="linkColor" href="' + articleMonthUrl + obj.releaseTime + '"> ' + obj.releaseTime + '</a></i>' +
                '</div>' +
                '<div class="originalAuthor">' +
                '<i class="am-icon-user"> ' + obj.createBy + '</i>' +
                '</div>' +
                '<div class="categories">' +
                '<i class="am-icon-folder"><a class="linkColor" href="/categories?category=' + obj.catalogId + '"> ' + obj.catalogName + '</a></i>' +
                '</div>' +
                '</div>' +
                '</header>' +
                '<div class="article-entry" id = "content_' + obj.id + '"></div>' +
                '<div class="read-all">' +
                '<a href="' + articleDetilUrl + obj.id + '" target="_blank">阅读全文 <i class="am-icon-angle-double-right"></i></a>' +
                '</div>' +
                '<hr>' +
                '<div class="article-tags"></div>' +
                '</div>');
            articles.append(center);
            var articleTags = $('.article-tags');
            var tagStr = obj.articleTags;
            if (tagStr.length > 0) {
                var tags = tagStr.split(",");
                for (var i = 0; i < tags.length; i++) {
                    //todo 缺少接口
                    var articleTag = $('<i class="am-icon-tag"><a class="tag" href="/tags?tag=' + tags[i] + '"> ' + tags[i] + '</a></i>');
                    articleTags.eq(index).append(articleTag);
                }
            }
            editormd.markdownToHTML("content_" + obj.id, {
                markdown: obj.desca,
                htmlDecode: "style,script,iframe",
                tocm: true,
                emoji: true,
                taskList: true,
                tex: true,
                flowChart: true,
                sequenceDiagram: true
            });
            //$("#content_" + obj.id).html(obj.content);
        }
    })
}

//填充网站通知
function notice() {
    $.ajax({
        type: 'GET',
        url: '/front/index/notice',
        dataType: 'json',
        success: function (data) {
            if (data.code == 0) {
                $("#noticeInfo").append(data.data.content);
            }
        },
        error: function () {
            alert("获得通知信息失败！");
        }
    });
}

//填充最新评论
function putInNewComment(data) {
    var newComment = $('.new-comment');
    newComment.empty();
    var listNews = $('<div data-am-widget="list_news" class="am-list-news am-list-news-default" ></div>');
    var newCommentTitle = $('<div class="am-list-news-hd am-cf">' +
        '<a class="newComments">' +
        '<h2 style="color: #110101">最新评论</h2>' +
        '</a>' +
        '</div>');
    listNews.append(newCommentTitle);
    var amListNewsBd = $('<div class="am-list-news-bd"></div>');
    var ul = $('<ul class="fiveNewComments am-list"></ul>');
    $.each(data, function (index, obj) {
        var li = $('<li class="am-g am-list-item-dated">' +
            '<a class="newCommentTitle" target="_blank" href="' + articleDetilUrl + obj['articleId'] + '#p' + obj['id'] + '" class="am-list-item-hd" style="padding-bottom: 5px" title="' + obj['articleTitle'] + '">' + obj['articleTitle'] + '</a>' +
            '<span class="am-list-date">' + obj['createTime'] + '</span>' +
            '<div class="new-comment-content" style="margin-bottom: 5px;">' + obj['userName'] + '：' + obj['content'] + '</div>' +
            '</li>');
        ul.append(li);
    });
    amListNewsBd.append(ul);
    listNews.append(amListNewsBd);
    newComment.append(listNews);
    newComment.append($('<div class="my-row" id="page-father">' +
        '<div class="newCommentPagination">' +
        '</div>' +
        '</div>'));
}

//填充最新留言
function putFeedBackWord(data) {
    var newLeaveWord = $('.new-leaveWord');
    newLeaveWord.empty();
    var listNews = $('<div data-am-widget="list_news" class="am-list-news am-list-news-default" ></div>');
    var newCommentTitle = $('<div class="am-list-news-hd am-cf">' +
        '<a class="newLeaveWord">' +
        '<h2 style="color: #110101">最新反馈</h2>' +
        '</a>' +
        '</div>');
    listNews.append(newCommentTitle);
    var amListNewsBd = $('<div class="am-list-news-bd"></div>');
    var ul = $('<ul class="fiveNewComments am-list"></ul>');
    $.each(data, function (index, obj) {
        ul.append($('<li class="am-g am-list-item-dated">' +
            '<a class="newLeaveWordTitle" href="#">' + obj['userName'] + '：' + obj['content'] + '</a>\n' +
            '<span class="am-list-date">' + obj['createTime'] + '</span>' +
            '</li>'));
    });
    amListNewsBd.append(ul);
    listNews.append(amListNewsBd);
    newLeaveWord.append(listNews);
    newLeaveWord.append($('<div class="my-row" id="page-father">' +
        '<div class="newLeaveWordPagination">' +
        '</div>' +
        '</div>'));
}

//添加标签云
function putInTagsCloud(data) {
    var tagCloud = $('.tag-cloud');
    tagCloud.empty();
    tagCloud.append($('<h3 class="widget-title">标签云</h3>'));
    var widgetTagCloud = $('<div class="widget-tag-cloud"></div>');
    $.each(data['result'], function (index, obj) {
        widgetTagCloud.append($('<a href="tags?tag=' + obj['tagName'] + '" style="font-size:' + obj['tagSize'] + 'px">' + obj['tagName'] + '</a>'));
    });
    tagCloud.append(widgetTagCloud);
}

//首页文章分页请求
function ajaxFirst(currentPage) {
    var param = {
        pageSize: "5",
        pageNum: currentPage
    }
    //加载时请求
    $.ajax({
        type: 'POST',
        url: '/front/index/articles',
        dataType: 'json',
        data: param,
        success: function (data) {
            if (data.code != 0) {
                dangerNotice("服务器异常，获得文章信息失败");
            } else {
                //放入数据
                putInArticle(data.rows);
                scrollTo(0, 0);//回到顶部
                //分页
                $("#pagination").paging({
                    rows: param.pageSize,//每页显示条数
                    pageNum: param.pageNum,//当前所在页码
                    pages: Math.ceil(data.total / param.pageSize),//总页数
                    total: data.total,//总记录数
                    callback: function (currentPage) {
                        ajaxFirst(currentPage);
                    }
                });
            }
        },
        error: function () {
            alert("获得文章信息失败！");
        }
    });
}

function newCommentAjax(currentPage) {
    var param = {
        pageSize: "5",
        pageNum: currentPage
    }
    //最新评论
    $.ajax({
        type: 'POST',
        url: '/front/index/newComments',
        dataType: 'json',
        data: param,
        success: function (data) {
            putInNewComment(data['rows']);
            //分页
            $(".newCommentPagination").paging({
                rows: param.pageSize,//每页显示条数
                pageNum: param.pageNum,//当前所在页码
                pages: Math.ceil(data.total / param.pageSize),//总页数
                total: data.total,//总记录数
                callback: function (currentPage) {
                    newCommentAjax(currentPage);
                }
            });

        },
        error: function () {
        }
    });
}

function newFeedBackAjax(currentPage) {
    var param = {
        pageSize: "5",
        pageNum: currentPage
    }
    //最新留言
    $.ajax({
        type: 'POST',
        url: '/front/index/newFeedbacks',
        dataType: 'json',
        data: param,
        success: function (data) {
            putFeedBackWord(data['rows']);
            //分页
            $(".newLeaveWordPagination").paging({
                rows: param.pageSize,//每页显示条数
                pageNum: param.pageNum,//当前所在页码
                pages: Math.ceil(data.total / param.pageSize),//总页数
                total: data.total,//总记录数
                callback: function (currentPage) {
                    newFeedBackAjax(currentPage);
                }
            });
        },
        error: function () {
        }
    });
}

//点击扫描二维码时获取二维码图片
$('.myCardBtn').click(function () {
    $('.qq_code').attr("src", "/img/qq.png");
    $('.weixin_code').attr("src", "/img/vx.png");
});


//标签云
/*
$.ajax({
    type: 'GET',
    url: '/findTagsCloud',
    dataType: 'json',
    data: {},
    success: function (data) {
        if (data['data']['result'].length == 0) {
            var tagCloud = $('.tag-cloud');
            tagCloud.empty();
            tagCloud.append($('<h3 class="widget-title">标签云</h3>'));
            var widgetTagCloud = $('<div class="widget-tag-cloud"><span>暂无标签</span></div>');
            tagCloud.append(widgetTagCloud);
            $('#right').append(tagCloud);
        } else {
            putInTagsCloud(data['data']);
        }
    },
    error: function () {
    }
});
*/
//网站信息
/*
$.ajax({
    type: 'GET',
    url: '/getSiteInfo',
    dataType: 'json',
    data: {},
    success: function (data) {
        var siteInfo = $('.site-info');
        siteInfo.empty();
        siteInfo.append('<h5 class="site-title">' +
            '<i class="am-icon-info site-icon"></i>' +
            '<strong style="margin-left: 15px">网站信息</strong>' +
            '</h5>');
        var siteDefault = $('<ul class="site-default"></ul>');
        siteDefault.append('<li>' +
            '<i class="am-icon-file site-default-icon"></i><span class="site-default-word">文章总数</span>：' + data['data']['articleNum'] + ' 篇' +
            '</li>');
        siteDefault.append('<li>' +
            '<i class="am-icon-tags site-default-icon"></i><span class="site-default-word">标签总数</span>：' + data['data']['tagsNum'] + ' 个' +
            '</li>');
        siteDefault.append('<li>' +
            '<i class="am-icon-comments-o site-default-icon"></i><span class="site-default-word">留言总数</span>：' + data['data']['leaveWordNum'] + ' 条' +
            '</li>');
        siteDefault.append('<li>' +
            '<i class="am-icon-commenting-o site-default-icon"></i><span class="site-default-word">评论总数</span>：' + data['data']['commentNum'] + ' 条' +
            '</li>');
        siteDefault.append('<li>' +
            '<i class="am-icon-pencil-square site-default-icon"></i><span class="site-default-word">网站最后更新</span>：<span class="siteUpdateTime">' + siteLastUpdateTime + '</span>' +
            '</li>');
        siteDefault.append('<li>' +
            '<i class="am-icon-calendar site-default-icon"></i><span class="site-default-word">网站运行天数</span>：<span class="siteRunningTime"> </span>' +
            '</li>');
        siteInfo.append(siteDefault);

    },
    error: function () {
    }
});
*/
//网站运行时间
//beginTime为建站时间的时间戳
function siteRunningTime(time) {
    var theTime;
    var strTime = "";
    if (time >= 86400) {
        theTime = parseInt(time / 86400);
        strTime += theTime + "天";
        time -= theTime * 86400;
    }
    if (time >= 3600) {
        theTime = parseInt(time / 3600);
        strTime += theTime + "时";
        time -= theTime * 3600;
    }
    if (time >= 60) {
        theTime = parseInt(time / 60);
        strTime += theTime + "分";
        time -= theTime * 60;
    }
    strTime += time + "秒";

    $('.siteRunningTime').html(strTime);
}

var nowDate = new Date().getTime();
//网站开始运行日期
var oldDate = new Date(siteBeginRunningTime.replace(/-/g, '/'));
var time = oldDate.getTime();
var theTime = parseInt((nowDate - time) / 1000);
setInterval(function () {
    siteRunningTime(theTime);
    theTime++;
}, 1000);

$(function () {
    //初始化首页文章
    ajaxFirst(1);
    //初始化公告
    notice();
    //评论
    newCommentAjax(1);
    //留言
    newFeedBackAjax(1);

});
